/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.service.impl;

import me.zhengjie.constant.ConstantUtils;
import me.zhengjie.modules.system.domain.CourseApplicants;
import me.zhengjie.modules.web.enums.ApplicantsSignStatusEnum;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.system.repository.CourseApplicantsRepository;
import me.zhengjie.modules.system.service.CourseApplicantsService;
import me.zhengjie.modules.system.service.dto.CourseApplicantsDto;
import me.zhengjie.modules.system.service.dto.CourseApplicantsQueryCriteria;
import me.zhengjie.modules.system.service.mapstruct.CourseApplicantsMapper;
import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.sql.Timestamp;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author wangyu
* @date 2024-05-21
**/
@Service
@RequiredArgsConstructor
public class CourseApplicantsServiceImpl implements CourseApplicantsService {

    private final CourseApplicantsRepository courseApplicantsRepository;
    private final CourseApplicantsMapper courseApplicantsMapper;

    @Override
    public Map<String,Object> queryAll(CourseApplicantsQueryCriteria criteria, Pageable pageable){
        Page<CourseApplicants> page = courseApplicantsRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        Map<String, Object> resultMap = PageUtil.toPage(page.map(courseApplicantsMapper::toDto));
        if (MapUtils.isEmpty(resultMap)){
            return resultMap;
        }
        List<CourseApplicantsDto> applicantsDtos = (List<CourseApplicantsDto>)resultMap.get("content");
        applicantsDtos.forEach(s -> {
            Timestamp expireTime = s.getExpireTime();
            if (Objects.isNull(expireTime)){
                return;
            }
            if (expireTime.before(DateUtil.TimestampNow())){
                s.setSignStatus(ApplicantsSignStatusEnum.Expired.getSignStatus());
            }
        });
        return resultMap;
    }

    @Override
    public List<CourseApplicantsDto> queryAll(CourseApplicantsQueryCriteria criteria){
        return courseApplicantsMapper.toDto(courseApplicantsRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public CourseApplicantsDto findById(Long id) {
        CourseApplicants courseApplicants = courseApplicantsRepository.findById(id).orElseGet(CourseApplicants::new);
        ValidationUtil.isNull(courseApplicants.getId(),"CourseApplicants","id",id);
        return courseApplicantsMapper.toDto(courseApplicants);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CourseApplicantsDto create(CourseApplicants resources) {
        return courseApplicantsMapper.toDto(courseApplicantsRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(CourseApplicants resources) {
        CourseApplicants courseApplicants = courseApplicantsRepository.findById(resources.getId()).orElseGet(CourseApplicants::new);
        ValidationUtil.isNull( courseApplicants.getId(),"CourseApplicants","id",resources.getId());
        courseApplicants.copy(resources);
        if (ApplicantsSignStatusEnum.OffLine.getSignStatus().equals(resources.getSignStatus())){
            courseApplicants.setConsume(ConstantUtils.Valid);
        }
        if (ApplicantsSignStatusEnum.NotSign.getSignStatus().equals(resources.getSignStatus())){
            courseApplicants.setConsume(ConstantUtils.InValid);
        }
        courseApplicantsRepository.save(courseApplicants);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            courseApplicantsRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<CourseApplicantsDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (CourseApplicantsDto courseApplicants : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("课程编号", courseApplicants.getCourseNo());
            map.put("课程名称", courseApplicants.getCourseName());
            map.put("用户openId", courseApplicants.getOpenId());
            map.put("用户名称", courseApplicants.getRealName());
            map.put("手机号", courseApplicants.getMobile());
            map.put("创建时间", courseApplicants.getCreateTime());
            map.put("用户昵称", courseApplicants.getNickName());
            map.put("是否支付", courseApplicants.getPaid());
            map.put("是否核销", courseApplicants.getConsume());
            map.put("订单号", courseApplicants.getOrderNo());
            map.put("过期时间", courseApplicants.getExpireTime());
            map.put("是否本人", courseApplicants.getOneself());
            map.put("签到状态，0：未签到，1：线上签到，2：线下补录，3：过期", courseApplicants.getSignStatus());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}